package com.LGF.Book.biz;

import com.LGF.Book.bean.Book;
import com.LGF.Book.bean.BookType;
import com.LGF.Book.bean.Member;
import com.LGF.Book.bean.Record;
import com.LGF.Book.dao.BookDao;
import com.LGF.Book.dao.BookTypeDao;
import com.LGF.Book.dao.MemberDao;
import com.LGF.Book.dao.RecordDao;
import com.LGF.Book.util.DBHelper;
import com.LGF.Book.util.DateHelper;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RecordBiz {
    RecordDao recordDao = new RecordDao();
    BookDao bookDao = new BookDao();
    MemberDao memberDao = new MemberDao();
    MemberBiz memberBiz = new MemberBiz();
    BookTypeDao bookTypeDao = new BookTypeDao();
    BookTypeBiz bookTypeBiz = new BookTypeBiz();
    /**
     * 调用dao层根据会员id获取会员借阅信息
     * @param memId
     * @return
     */
    public List<Record> getRecordByMemberId(long memId){
        List<Record> records = null;
        try {
            records = recordDao.getRecordByMemberId(memId);

            //获取会员对象
            Member member1 = memberBiz.getById(memId);

            for (Record record : records){
                long bookId = record.getBookId();
                Book book = bookDao.getById(bookId);
                BookType bookType = bookTypeBiz.getById(book.getTypeId());
                book.setType(bookType);
                record.setBook(book);
                record.setMember(member1);

//                //计算应还时间
//                //先查出会员最大归还天数
//                long day = member1.getType().getKeepDay();
//                //做时间计算
//                java.sql.Date rentDate = record.getRentDate();
//                //转成毫秒数
//                java.sql.Date backDate = DateHelper.getNewDate(rentDate,day);
//
//                //算好后重新设置归还时间
//                record.setBackDate(backDate);

            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;

    }

    /**
     *调用dao层根据会员id获取所有会员记录
     * @param memId
     * @return
     */
    public List<Record> getAllMemId(long memId){
        List<Record> records = null;
        try {
            records = recordDao.getAllMemId(memId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;

    }

    /**
     * 调用dao层根据会员id和图书id查询借阅信息，归还时间为null
     * @param memId
     * @param bookList
     * @return
     */
    public int getById(long memId,List<Long> bookList ){


            //拿到借阅的书籍编号
            for (long bookId:bookList) {
                try {
                    Record record = recordDao.getById(memId, bookId);
                    if (record==null){
                        return 0;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    return 0;
                }
            }

            return 1;
    }

    /**
     * 借阅
     * 1.借一本书：record表添加一行信息（recordDao,insert）
     * 2.这本书的数量-1 (bookDao,update)
     * 3.会员信息表中，更改余额(memeberDao,update)
     * 一个整体的业务 要么全部成功，要么全部失败
     * 前提是 ：整体业务用一个Connection对象
     * @param memId
     * @param bookList
     * @param userId
     * @return
     */
    public int add(long memId,List<Long> bookList,long userId){

        try {
            //1.启动事务
            DBHelper.beginTransaction();
            double total = 0;
            //拿到借阅的书籍编号
            for (long bookId:bookList){
                Record record = recordDao.getById(memId, bookId);
                //调用bookbiz层 根据图书id获取book对象
                Book book = bookDao.getById(bookId);
                //调用价格 根据图书的价格*0.2 算出借阅需要的押金
                float price = book.getPrice();
                //每本书的押金
                float regPrice = price *0.2f;
                //调用memberDao层根据memId获取会员会员类型折扣信息
                Member mem = memberBiz.getById(memId);
                double discount = mem.getType().getDiscount();
                System.out.println("discount"+discount);
                regPrice= (float) (regPrice*discount*0.01);
                //一共借的书押金总和
                total+=regPrice;
                //调用recordDao层 add 添加一个借阅记录信息
                recordDao.add(memId,bookId,regPrice,userId);
                //调用bookDao层 modfiy 更新图书的库存量
                bookDao.modify(bookId,-1);
            }

           /* total=total*discount*0.01;*/
            //调用memberDao层方法修改会员的余额
            memberDao.modifyBalance(memId,0-total);
            //事务结束
            DBHelper.commitTransaction();//事务提交：成功
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                DBHelper.rollbackTransaction();//事务回滚：有异常
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            return 0;
        }


        return 1;

    }

    public static void main(String[] args) {
        //getById(long memId,List<Long> bookList )
        RecordBiz recordBiz = new RecordBiz();
        List<Long> longs = new ArrayList<Long>();
        long id= 1001;
        long ids= 1006;
        longs.add(id);
        longs.add(ids);
        long memId = 2022001;
        int count = recordBiz.getById(memId, longs);

        System.out.println("count:"+count);
    }

    public List<Record> getPageByMemId(long memId,int page,int limit){
        List<Record> records = null;
        try {
            records = recordDao.getPageByMemId(memId, page, limit);

            //获取会员对象
            Member member = memberBiz.getById(memId);

            for (Record record : records){
                long bookId = record.getBookId();
                Book book = bookDao.getById(bookId);
                BookType bookType = bookTypeBiz.getById(book.getTypeId());
                book.setType(bookType);
                record.setBook(book);
                record.setMember(member);

//                //计算应还时间
//                //先查出会员最大归还天数
//                long day = member.getType().getKeepDay();
//                //做时间计算
//                java.sql.Date rentDate = record.getRentDate();
//                //转成毫秒数
//                java.sql.Date backDate = DateHelper.getNewDate(rentDate,day);
//
//                //算好后重新设置归还时间
//                record.setBackDate(backDate);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }

    /**
     * 调用Dao方法根据id更新归还时间
     * @param id
     * @return
     */
    public int modify(long id){
        int count = 0;
        try {
            count = recordDao.modify(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;

    }

    /**
     * 归还功能
     * 1.recordDao modify：押金，归还日期，操作员的编号
     * 2.memberDao modify：余额
     * 3.书籍信息表 modify：数量
     * 成功：提交
     * 失败：回滚
     * @param memId
     * @param recordIds
     * @param userId
     * @return 1：成功 0：失败
     */
    public int modify(long memId,List<Long> recordIds,long userId){
        //开启事务
        try {
            DBHelper.beginTransaction();
            double total = 0;
            Member member = memberBiz.getById(memId);
            for (long recordId:recordIds){
                //通过记录编号获取记录对象
                Record record = recordDao.getById(recordId);
                //计算押金 累加押金之后更改押金  （逾期：超出一天扣一块）
                java.sql.Date backDate = DateHelper.getNewDate(record.getRentDate(),member.getType().getKeepDay());
                System.out.println(backDate);
                //获取系统当前时间
                java.util.Date currentDate = new java.util.Date();
                System.out.println(currentDate);
                int day =0;
                if (currentDate.after(backDate)){
                    //计算押金
                     day = DateHelper.getSpan(backDate, currentDate);
                }
                total += record.getDeposit()-day;
                System.out.println(total);
                //更该record
                recordDao.modify(day,userId,recordId);
                //修改书籍数 +1
                bookDao.modify(record.getBookId(),1);
            }
            //修改余额
            memberDao.modifyBalance(memId,total);
            DBHelper.commitTransaction();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                DBHelper.rollbackTransaction();
            } catch (SQLException ex) {
                ex.printStackTrace();
                return 0;
            }
        }
        return 1;
    }

    /**
     * 调用dao层根据会员id获取记录信息
     * @param memId
     * @return
     */
    public List<Record> getByIds(long memId){
        List<Record> records = null;
        try {
            records = recordDao.getByIds(memId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }

    /**
     * 多条件查询信息
     * @param search
     * @return
     */
    public List<Map<String, Object>> conditionSearch(String search){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.conditionSearch(search);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;

    }

    /**
     * 查询所有记录信息
     * @return
     */
    public List<Map<String, Object>> searchAll(){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.searchAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;

    }

    /**
     * 分页查询记录信息
     * @param page
     * @param limit
     * @return
     */
    public List<Map<String, Object>> getByPage(int page,int limit){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.getByPage(page, limit);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 多条件分页查询记录信息
     * @param page
     * @param limit
     * @param search
     * @return
     */
    public List<Map<String, Object>> conditionSearchByPage(int page ,int limit,String search){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.conditionSearchByPage(page, limit, search);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 调用dao层 根据会员id 分页查询会员记录信息
     * @param memId
     * @param page
     * @param limit
     * @return
     */
    public List<Map<String, Object>> getByPageMemId( long memId,int page,int limit){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.getByPageMemId(memId, page, limit);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;

    }

    /**
     * 调用dao层 根据会员id 查询会员所有的记录信息
     * @param memId
     * @return
     */
    public List<Map<String, Object>> selectByMemId(long memId){
        List<Map<String, Object>> data = null;
        try {
            data = recordDao.selectByMemId(memId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;
    }



}
